package GUI;

import Ctr.AttendanceCtr;
import Ctr.LoginCtr;
import Model.Course;
import Model.Student;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

public class AttendanceGUI extends JFrame {
    private String date;
    private JPanel contentPane;
    private JPanel pnlStudentInfo;
    private JPanel pnlAttendance;
    private JLabel lblStudentWelcome;
    private JLabel lblCurrentDate;
    private JButton btnCheckin;
    private JList lstAttendance;
    private Student studentAttendance;
    private Date currentDate;
    private AttendanceCtr attendanceCtr;
    private LoginCtr loginCtr;

    public AttendanceGUI(Student student, String date) {
        setContentPane(contentPane);
        setSize(800, 600);
        setVisible(true);
        setTitle("UCN Attendance");
        studentAttendance = student;
        this.date = date;
        updateLabels();
        showAttendanceList();
        attendanceCtr = new AttendanceCtr();
        loginCtr = new LoginCtr();

        btnCheckin.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                studentCheckIn();
            }
        });
    }

    public void updateLabels() {
        String timeStamp = new SimpleDateFormat("dd/MM/yyyy").format(Calendar.getInstance().getTime());
        lblStudentWelcome.setText("Welcome " + studentAttendance.getName());
        lblCurrentDate.setText(timeStamp);
    }

    public void showAttendanceList() {
        DefaultListModel dlm = new DefaultListModel();
        AttendanceCtr attendanceCtr = new AttendanceCtr();

        ArrayList<Course> courseList = attendanceCtr.getAllCoursesForOneStudent(studentAttendance);

        for (Course c : courseList) {
            if (c.getId() != 0) {
                String attendance1 = c.getName() + ": " + attendanceCtr.getCourseAttendanceByIDAndDate(studentAttendance, c.getId(), date) + "%";
                dlm.addElement(attendance1);
            }
        }

        dlm.addElement("Samlet: " + attendanceCtr.getAllAttendanceForOneStudentByIDAndDate(studentAttendance, date) + "%");

        lstAttendance.setModel(dlm);
    }

    private void studentCheckIn() {
        System.out.println(studentAttendance.getName());
        System.out.println(studentAttendance.getPassword());
        try {
            attendanceCtr.studentCheckIn(loginCtr.studentLogin(studentAttendance.getUsername(), studentAttendance.getPassword()), date);
        }
        catch (NullPointerException npe) {
            warningWindow("Ingen lektioner i dag");
        }
    }

    private void warningWindow(String message) {
        JOptionPane.showMessageDialog(pnlAttendance, "" + message);
    }
}
